package d6.offer32_2;

import com.jieshen.TreeNode;
import com.jieshen.utils.BinaryTree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 二叉树的每一层的节点数，作为二维列表的一个元素。
 *
 */
public class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> tmp;
        Queue<TreeNode> nodeQueue = new LinkedList<>();
        if (root == null) {
            return res;
        }
        nodeQueue.add(root);
        while (!nodeQueue.isEmpty()) {
            //这一层的node数
            int size = nodeQueue.size();
            tmp = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode node = nodeQueue.remove();
                tmp.add(node.val);
                if (node.left != null)
                    nodeQueue.add(node.left);
                if (node.right != null)
                    nodeQueue.add(node.right);
            }
            res.add(tmp);
        }
        return res;
    }

    public static void main(String[] args) {
        Integer[] arr = {3, 9, 20, null, null, 15, 7};
        TreeNode treeNode = new BinaryTree().BuildTree(arr);
        List<List<Integer>> lists = new Solution().levelOrder(treeNode);
        for (List<Integer> list : lists) {
            for (Integer l : list) {
                System.out.print(l + " ");
            }
            System.out.println();
        }
    }
}
